<?php
$pwd2Err=$uidErr="";
$uid=$pwd=$pwd2="";
if($_SERVER["REQUEST_METHOD"]=="POST"){
    $uid=test_input($_POST["uid"]);
    $pwd=test_input($_POST["pwd"]);
    $pwd2=test_input($_POST["pwd2"]);
    if($pwd2!=$pwd){
        $pwd2Err="密码不一致";
        die("error1");
    }
    else{
        $host="localhost";
        $user="root";
        $password="wcn4911.";
        $database="muban_php";
        $conn=new mysqli($host,$user,$password,$database);
        if($conn->connect_error){
            die($conn->connect_error);
        }
        else{
            $sql="select * from user where uid='".$uid."'";
            $result=$conn->query($sql);
            if($result->num_rows==1){
                echo "<script type='text/javascript'>alert('用户名已存在');location='javascript:history.back()';</script>"; 
            }
            else{
                $sql="insert into user (uid,pwd) values ('".$uid."','".$pwd."')";
                echo $sql;
                if(true==$conn->query($sql)){
                    setcookie("user",$uid);
                    echo "<script>location.href='index.php'</script>";
                }
                else{
                    die("error2");
                }
            }
            
        }
    }
    
}

function test_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <link type="text/css" href="css/base.css">
        <script src="js/base.js"></script>
        <title>注册</title>
    </head>
    <body>
        <div class="main">
            
            <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                <input type="text" name="uid" placeholder="用户名" required="required"/><?php echo $uidErr; ?><br>
                <input type="password" name="pwd" placeholder="密码" required="required"/><br>
                <input type="password" name="pwd2" placeholder="确认密码" required="required"/><?php echo $pwd2Err; ?><br>
                <input type="submit" value="注册">
            </form>
            
        </div>
    </body>
</html>